package com.treasure.hunt.goods

import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.module.lemlin.base.loadCropImage
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.code
import com.module.lemlin.rxhttp.msg
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.Action
import com.treasure.hunt.entity.Category
import com.treasure.hunt.entity.Goods
import com.treasure.hunt.entity.MainBean
import com.treasure.hunt.mine.MineConfigActivity
import com.treasure.hunt.mode.GoodsViewMode
import com.treasure.hunt.popup.DialogFlopPopup
import com.treasure.hunt.popup.DialogHintPopup
import kotlinx.android.synthetic.main.fragment_goods_home.*
import org.greenrobot.eventbus.EventBus

class GoodsHomeFragment : ViewModeFragment<GoodsViewMode>() {

    companion object {
        private const val EXTRA_NAME_CATEGORY = "EXTRA_NAME_CATEGORY"
        private const val EXTRA_NAME_SEARCH = "EXTRA_NAME_SEARCH"
        fun newInstance(category: Category): GoodsHomeFragment {
            val bundle: Bundle = Bundle().apply {
                putSerializable(EXTRA_NAME_CATEGORY, category)
            }
            return GoodsHomeFragment().apply {
                arguments = bundle
            }
        }

        fun newInstance(search: String): GoodsHomeFragment {
            val bundle: Bundle = Bundle().apply {
                putString(EXTRA_NAME_SEARCH, search)
            }
            return GoodsHomeFragment().apply {
                arguments = bundle
            }
        }
    }

    private var mGoods: Goods? = null

    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = requireContext(),onAnimationEnd = {})
    }
    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = requireContext(),
            onConfirm = { view, type ->
                if (type == DialogHintPopup.Type.SHOW_SYNTHESIS) {
                    mGoods?.let {
                        viewModel.indexSynthesisGoods(it.id)
                    }
                } else if (type == DialogHintPopup.Type.SHOW_HUNT) {
                    val mainBean: MainBean<Action, Any> = MainBean(
                        type = Action.GO_HUNT
                    )
                    EventBus.getDefault().post(mainBean)
                }
                hintPopup.dismiss()
            },
            onCancel = { view, type ->
                hintPopup.dismiss()
            })
    }


    private val errorPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = requireContext(),
            onConfirm = { view, type ->
                errorPopup.dismiss()
            },
            onCancel = { view, type ->
                errorPopup.dismiss()
            })
    }

    private val goodsHomeAdapter =
        object : BaseQuickAdapter<Goods, BaseViewHolder>(R.layout.item_goods_home) {

            init {
                addChildClickViewIds(R.id.tvGoodsGoHunt, R.id.tvGoodsSynthesis, R.id.ivGoodsCollect)
            }

            override fun convert(holder: BaseViewHolder, item: Goods) {
                holder.setText(R.id.tvGoodsName, item.title)
                    .setText(R.id.tvGoodsNum, "x${item.cart_num}")
                    .setText(R.id.tvGoodsDiff, "差${item.difference}张")
                    .setGone(R.id.tvGoodsDiff, item.is_synthesis != 0)
                    .setGone(R.id.tvGoodsGoHunt, item.is_synthesis != 0)
                    .setGone(R.id.tvGoodsSynthesis, item.is_synthesis != 1)

                holder.getView<ImageView>(R.id.ivGoodsCollect).let {
                    if (item.is_collection == 0) {
                        it.setImageResource(R.mipmap.ic_23317)
                    } else {
                        it.setImageResource(R.mipmap.ic_23316)
                    }
                }

                val isHttps: Boolean = item.image.substring(0, 5).contains("http") ||
                        item.image.substring(0, 5).contains("https")
                holder.getView<ImageView>(R.id.ivGoodsIcon)
                    .loadRoundImage(
                        "${if (isHttps) "" else AppConstance.URL_IMAGE}${item.image}", radius = 10
                    )
                val isHttps2: Boolean = item.cartconfig.image.substring(0, 5).contains("http") ||
                        item.cartconfig.image.substring(0, 5).contains("https")
                holder.getView<ImageView>(R.id.ivGoodsNumIcon)
                    .loadCropImage(
                        "${if (isHttps2) "" else AppConstance.URL_IMAGE}${item.cartconfig.image}"
                    )
            }
        }

    private var mCategory: Category? = null
    private var mSearch: String? = null

    override fun viewModel(): GoodsViewMode {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_goods_home

    override fun initView() {
        mCategory = arguments?.getSerializable(EXTRA_NAME_CATEGORY) as? Category
        mSearch = arguments?.getString(EXTRA_NAME_SEARCH, null)

        rvGoodsHomeBody.adapter = goodsHomeAdapter.apply {
            animationEnable = true
            setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom)
            goodsHomeAdapter.setEmptyView(createLoadingView())
        }

        goodsHomeAdapter.setOnItemChildClickListener { adapter, view, position ->
            val itemData: Goods = goodsHomeAdapter.getItem(position)
            if (view.id == R.id.tvGoodsGoHunt) {
                val maps: MutableMap<String, Any?> = mutableMapOf(
                    "advertisement_type" to 5,
                    "luck_draw_type" to 1
                )
                viewModel.videoType(maps)
            } else if (view.id == R.id.tvGoodsSynthesis) {
                mGoods = itemData
                hintPopup.setType(DialogHintPopup.Type.SHOW_SYNTHESIS).setText(
                    textTitle = "温馨提示",
                    textMessage = "合成该商品需要消耗${itemData.cart_num}张“${itemData.ctitle}”，合成概率为${itemData.actual_probability}%\n确认合成吗？",
                    textConfirm = "立即合成",
                    textCancel = "知道了"
                )
                    .showPopupWindow()
            } else if (view.id == R.id.ivGoodsCollect) {
                viewModel.indexAddGoodsCollection(itemData.id)
            }
        }


        mSmartRefreshHeader.setColorSchemeResources(R.color.colorMain)
//        mSmartRefreshLayout.setEnableRefresh(false)
        mSmartRefreshLayout.setEnableLoadMore(false)
        mSmartRefreshLayout.setOnRefreshListener {
            viewModel.indexGetGoods()
        }
        mSmartRefreshLayout.setOnLoadMoreListener {
            viewModel.indexGetGoods(isLoadMore = true)
        }
    }

    override fun initData() {

        mCategory?.let {
            viewModel.mGoodsRequest.apply {
                category_id = it.id
            }
            viewModel.indexGetGoods()
        }

        mSearch?.let {
            viewModel.mGoodsRequest.apply {
                search = it
            }
            viewModel.indexGetGoods()
        }

    }

    override fun initViewMode() {
        viewModel.goodsLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                mSmartRefreshLayout.finishLoadMore((false))
                mSmartRefreshLayout.finishRefresh((false))
                goodsHomeAdapter.setEmptyView(createEmptyView(response.throwable?.msg))
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            mSmartRefreshLayout.finishLoadMore()
            mSmartRefreshLayout.finishRefresh()
            response.httpData?.let {
                if (it.data.size == 0) {
                    goodsHomeAdapter.setEmptyView(createEmptyView())
                }
                if (it.loadMore) {
                    goodsHomeAdapter.addData(it.data)
                } else {
                    goodsHomeAdapter.setNewInstance(it.data)
                }
                if (it.data.size < viewModel.mGoodsRequest.limit) {
                    goodsHomeAdapter.setFooterView(createFooterView())
                    mSmartRefreshLayout.setEnableLoadMore(false)
                } else {
                    goodsHomeAdapter.removeAllFooterView()
                    mSmartRefreshLayout.setEnableLoadMore(true)
                }
            }
        })

        viewModel.goodsCollectionLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let { httpData ->
                if (httpData.data.code == 1) {
                    toast("收藏成功")
                } else {
                    toast("取消收藏")
                }
                goodsHomeAdapter.data.find { it.id == httpData.goodsId }
                    ?.apply { is_collection = httpData.data.code }
                goodsHomeAdapter.notifyDataSetChanged()
            }
        })

        viewModel.synthesisLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                val errorMsg: String = response?.throwable?.msg ?: "未知错误"
                if (response?.throwable?.code == 0) {
                    errorPopup.setText(
                        textTitle = "提示",
                        textMessage = errorMsg,
                        textConfirm = "确定",
                        textCancel = "取消"
                    ).setGoneTextCancel(true)
                        .showPopupWindow()
                } else {
                    toast(errorMsg)
                }
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                MineConfigActivity.openUrl(requireActivity(), null, it.url)
            }
        })


        viewModel.videoTypeLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
                ?: return@Observer
            val codeId: String? = response.httpData?.data?.advertising_space
            if (codeId == null) {
                toast("广告位ID为空")
            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = requireActivity(), codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = requireActivity(), codeId = codeId)
            }
        })

        viewModel.videoEndLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
//                flopPopup.fillData(it.data).showPopupWindow()
//                viewModel.loadNativeExpressAdCSJ(requireActivity())

                hintPopup.setType(DialogHintPopup.Type.SHOW_HUNT).setText(
                    textTitle = "温馨提示",
                    textMessage = "恭喜您获得" + it.data.text,
                    textConfirm = "去寻宝",
                    textCancel = "知道了"
                )
                    .showPopupWindow()
                initData()
            }
        })

        viewModel.rewardVerifyAdLiveData.observe(this, Observer { isRewardVerify ->
            if (!isRewardVerify)
                return@Observer
            viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                viewModel.videoEnd(it.video_log_id)
            }
        })

        viewModel.viewAdLiveData.observe(this, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })
    }

    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }

    private fun createEmptyView(message: String? = null): View {
        return layoutInflater.inflate(R.layout.view_empty_error, null).apply {
            if (message != null)
                findViewById<TextView>(R.id.tvEmptyMessage).text = message
        }
    }

    private fun createFooterView(): View = TextView(requireContext()).apply {
        layoutParams = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            ConvertUtils.dp2px(30f)
        )
        gravity = Gravity.CENTER
        textSize = 13f
        text = "没有更多数据"
        setTypeface(null, Typeface.BOLD)
        setTextColor(ColorUtils.getColor(R.color.FF_8587AA))
    }
}